﻿package com.thaiflashdev.net 
{
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	import flash.net.URLVariables;
	/**
	 * ...
	 * @author heart (heart@howdoflash.net)
	 */
	public class HTTPSender extends EventDispatcher
	{
		private var appUrl:URLRequest;
		private var meth:String="";
		private var variables:URLVariables;
		private var strURL:String = "";
		private var recivedata:String = "";
		/**
		 * 
		 * @param	url   your application address
		 * @param	methode post or get
		 */
		public function HTTPSender(url:String="",methode:String="post") 
		{
			if (url != "") {
				strURL = url;
				appUrl = new URLRequest(url);
			}
			if (methode != "") {
				if(methode.toLowerCase() != "get" &&  methode.toLowerCase() != "post"){
					throw Error("Methode Must Be GET or POST.");
				}else {
					meth = methode.toLowerCase();
				}
			}
			variables = new URLVariables();
		}
		public function addVar(name:String , value:String):void {
			variables[name] = value;
		}
		public function addVarObject(obj:Object):void {
			for (var i:String in obj) {
				variables[i] = obj[i];
			}
		}
		/**
		 * Sending Data
		 * @param	url your application address
		 * @param	methode post or get
		 */
		public function send(url:String = "", methode:String = ""):void {
			if (methode != "") {
				if(methode.toLowerCase() != "get" &&  methode.toLowerCase() != "post"){
					throw Error("Methode Must Be GET or POST.");
				}else {
					meth = methode.toLowerCase();
				}
			}
			
			if (url != "") {
				strURL = url;
				appUrl = new URLRequest(url);
			}
			if (strURL != "") {
				//var req:URLRequest = new URLRequest(appUrl);
				appUrl.method = meth;
				appUrl.data = variables;
				var loader:URLLoader = new URLLoader();
				loader.addEventListener(Event.COMPLETE , onComplete );
				loader.load(appUrl);
			}else {
				throw new Error("No URL Address.");
			}
			trace("sending");
		}
		private function onComplete(e:Event):void {
			recivedata = e.target.data;
			dispatchEvent(new Event(Event.COMPLETE));
		}
		public function get data():String {
			return recivedata;
		}
		
	}

}